package com.lqf.redpackage.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = {"com.lqf.redpackage.dao"}, sqlSessionTemplateRef = "testSqlSessionTemplate")
public class RootConfig implements ApplicationContextAware {

    private ApplicationContext ctx;

    @Bean("testSqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory(@Qualifier("test") DataSource crmDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(crmDataSource);
        factoryBean.setTypeAliasesPackage("com.lqf.redpackage.domain");
        Resource[] resources = ctx.getResources("classpath*:/mapper/*.xml");
        factoryBean.setMapperLocations(resources);
        return factoryBean;
    }

    @Bean("testSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory
                                                            sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("txManager")
    public DataSourceTransactionManager txManager(@Qualifier("test") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean("test")
    @ConfigurationProperties("druid.test")
    public DataSource crmDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
}
